package com.wuxiaolong.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.wuxiaolong.wechat.common.Constants;
import com.wuxiaolong.wechat.model.baidu.CharacterRecognitionResp;
import com.wuxiaolong.wechat.service.BaiduService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author Leo
 * @date 2020-02-13
 */
@Service
@Slf4j
public class BaiduServiceImpl implements BaiduService {

    @Value("${baidu.appId}")
    private String appId;

    @Value("${baidu.apiKey}")
    private String apiKey;

    @Value("${baidu.secretKey}")
    private String secretKey;

    @Override
    public String characterRecognition(Map<String, String> requestMap){
        try {
            // 初始化一个AipOcr
            AipOcr client = new AipOcr(appId, apiKey, secretKey);

            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);

            // 网上图片
            String path = requestMap.get("PicUrl");
            org.json.JSONObject res = client.generalUrl(path, new HashMap<String,String>());

            CharacterRecognitionResp resp = JSON.parseObject(res.toString(), CharacterRecognitionResp.class);

            StringBuilder sb = new StringBuilder();
            sb.append("图片文字识别结果：");
            for(CharacterRecognitionResp.Line map : resp.getWords_result()){
                sb.append(map.getWords());
            }
            return sb.toString();

        }catch (Exception e){
            log.error("百度普通文字识别失败",e);
            return Constants.BAIDU_CHARACTERE_COGNIZITON_DEFAULT_RESP;
        }

    }
}
